package com.king.modules.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.king.common.annotation.MvcData;
import com.king.common.constant.HttpStatus;
import com.king.common.constant.UserConstants;
import com.king.common.exception.AssertHelper;
import com.king.common.utils.SecurityUtils;
import com.king.framework.base.controller.YyTreeController;
import com.king.framework.base.domain.vo.AjaxResult;
import com.king.modules.system.domain.SysMenuEntity;
import com.king.modules.system.service.SysMenuService;

/**
 * 菜单信息
 * 
 * @author king
 */
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends YyTreeController<SysMenuEntity> {
	@Autowired
	private SysMenuService menuService;

	@PostMapping("/queryMenu")
	public AjaxResult queryMenu() {
		Long userId = SecurityUtils.getUserId();
		return menuService.selectRouteResByUserId(userId);
	}


	@Override
	protected Map<String, Object> addSearchParam(HttpServletRequest request) throws Exception {
		Map<String, Object> addParam = new HashMap<String, Object>();
		//菜单不区分groupid
//		if (!SecurityUtils.isAdmin()) {
//			addParam.put("EQ_groupid", SecurityUtils.getGroupid());
//		}
		return addParam;
	}

	@Override
	public AjaxResult deleteOne(HttpServletRequest request, @PathVariable("id") Long id) throws Exception {
		checkPermission();//判断权限
		return super.deleteOne(request, id);
	}

	@Override
	public AjaxResult delete(HttpServletRequest request, @RequestBody Long[] ids) throws Exception {
		checkPermission();//判断权限
		return super.delete(request, ids);
	}

	@Override
	public AjaxResult add(HttpServletRequest request, @RequestBody SysMenuEntity entity) throws Exception {
		checkPermission();//判断权限
		return super.add(request, entity);
	}

	@Override
	public AjaxResult update(HttpServletRequest request, @RequestBody SysMenuEntity entity) throws Exception {
		AssertHelper.getInstance().checkException(!SecurityUtils.isAdmin(), "没有权限");
		return super.update(request, entity);
	}

	
	/**
	 * 复制菜单
	 * @param entity
	 * @return
	 * @throws Exception 
	 */

	@PreAuthorize("@sps.hasAuthority('system:menu:edit')")
	@PostMapping("/copy")
	public AjaxResult copy(@RequestBody SysMenuEntity entity) throws Exception {
		return menuService.copy(entity.getId());
	}
	
	
	/**
	 * 查询菜单下按钮列表
	 * @param entity
	 * @return
	 * @throws Exception
	 */
	@PreAuthorize("@sps.hasAuthority('system:menu:edit')")
	@PostMapping("/menuRes/query")
	public AjaxResult menuResQuery(@RequestBody Map<String, Object> searchMap) throws Exception {
		return menuService.queryMenuRes(searchMap);
	}
	
	  /*
     * 新增保存
     *
     */
    @MvcData("新增")
    @PostMapping("/menuRes/add")
    public AjaxResult menuResAdd(HttpServletRequest request, @RequestBody SysMenuEntity entity) throws Exception {
    	AssertHelper.getInstance().checkNullException(entity.getParentid(), "请选择上级菜单");
    	SysMenuEntity parent = menuService.getById(entity.getParentid());
    	AssertHelper.getInstance().checkNullException(parent, "请选择上级菜单");
    	
    	SysMenuEntity menu = new SysMenuEntity();
    	menu.setMenutype(UserConstants.TYPE_BUTTON);
    	menu.setParentid(parent.getId());
    	menu.setIcon(UserConstants.TYPE_BUTTON_ICON);
    	menu.setPerms(entity.getPerms());
    	menu.setPath(entity.getPath());
    	menu.setNodename(entity.getNodename());
    	menu.setMemo(entity.getMemo());
    	
    	menuService.setBtnInfoByParent(menu, parent);
    	
        entity = menuService.doAdd(menu);
        return success(entity);
    }

    
    /*
     * 仅仅更新不为null的字段，如果字段为null，则不更新该字段值
     */
    @MvcData("更新")
    @PostMapping("/menuRes/update")
    public AjaxResult menuResUpdate(HttpServletRequest request, @RequestBody SysMenuEntity entity) throws Exception {
        if (entity == null) {
            return new AjaxResult(HttpStatus.ERROR, "实体" + persistentClass.getName() + "不存在，更新失败！");
        }
        
    	SysMenuEntity menu = menuService.getById(entity.getId());
    	SysMenuEntity parent = menuService.getById(entity.getParentid());
    	menu.setIcon(UserConstants.TYPE_BUTTON_ICON);
    	menu.setPerms(entity.getPerms());
    	menu.setPath(entity.getPath());
    	menu.setNodename(entity.getNodename());
    	menu.setMemo(entity.getMemo());
    	menuService.setBtnInfoByParent(menu, parent);
        
        entity = menuService.doUpdate(entity);
        return success(entity);
    }
    
    
    /*
     * 删除记录
     */
    @MvcData("删除")
    @GetMapping("/menuRes/delete/{id}")
    public AjaxResult menuResDeleteOne(HttpServletRequest request, @PathVariable("id") Long id) throws Exception {
    	SysMenuEntity entity = menuService.getById(id);
    	if(entity.getPath().equals("123321")){
    		//TODO 临时测试
            QueryWrapper<SysMenuEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("menutype", UserConstants.TYPE_BUTTON);
    		List<SysMenuEntity> btnList = menuService.list(queryWrapper);
            for(SysMenuEntity btn : btnList){
            	SysMenuEntity menu = menuService.getById(btn.getParentid());
            	btn.setPerms(menu.getPerms().substring(0, menu.getPerms().lastIndexOf(":")+1)+btn.getPath());
            	System.out.println(">>>>>>>>>>"+btn.getPerms());
            	menuService.updateById(btn);
            }
    	}
        
        baseService.doDelete(id);
        return success("操作成功");
    }

    /*
     * 批量删除
     *
     */
    @MvcData("批量删除")
    @PostMapping(value = "/menuRes/delete")
    public AjaxResult menuResDelete(HttpServletRequest request, @RequestBody(required = false) Long[] ids) throws Exception {
        if (ids == null || ids.length == 0) {
            return new AjaxResult(HttpStatus.ERROR, "删除失败：请选择删除的记录");
        }
        baseService.doDelete(ids);
        return success("操作成功");
    }
}